package com.ww.springboot.dd.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.ww.springboot.boot.utils.AssertUtil;
import com.ww.springboot.boot.utils.Func;
import com.ww.springboot.boot.utils.ObjectUtil;
import com.ww.springboot.boot.utils.StringUtil;
import com.ww.springboot.dd.dto.DealOmsDTO;
import com.ww.springboot.dd.dto.TenantDbDTO;
import com.ww.springboot.dd.enums.DealTypeEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.StringReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2024-10-26 09:19
 */
@Slf4j
@RestController
@RequestMapping("/deal")
@AllArgsConstructor
public class DealController {

    @PostMapping("/oms")
    public String oms(@RequestBody DealOmsDTO dto) {
        try {
            if (ObjectUtil.isEmpty(dto.getType())) {
                return "type不能为空:\n" + JSONUtil.toJsonStr(DealTypeEnum.format());
            }

            switch (DealTypeEnum.getEnumByType(dto.getType())) {
                case 大建云自提:
                    大建云自提(dto);
                    break;
            }
        } catch (Exception e) {
            return e.getMessage();
        }
        return "";
    }

    private void 大建云自提(DealOmsDTO dto) {
        AssertUtil.isTrue(StringUtil.isNotBlank(dto.getPackageCode()), "packageCode -包裹单号不能为空");
        AssertUtil.isTrue(StringUtil.isNotBlank(dto.getTenantId()), "tenantId -租户ID不能为空");

        List<String> list = Func.toStrList(dto.getPackageCode());

        String format = "update oms_package_main set warehouse_code = \"RESELLER,DJYZT,CK0040\"" +
                ",exception_type = \"2097193\",exception_msg = \"大建云自提单待处理，请导入成本数据\" " +
                ",package_status = 1 " +
                "where package_code in (\"%s\");";
        String sql = String.format(format, list.stream().collect(Collectors.joining("\",\"")));
        this.executorSql(sql, dto.getTenantId());
        this.syncEs(dto);
    }

    private void syncEs(DealOmsDTO dto) {
        if(ObjectUtil.isNotEmpty(dto.getOmOrderId())){
            this.syncOrderEs(dto.getTenantId(),dto.getOmOrderId());
        }
        if(ObjectUtil.isNotEmpty(dto.getPackageCode())){
            this.syncPackageEs(dto.getTenantId(),dto.getPackageCode());
        }
    }

    private void syncPackageEs(String tenantId,String packageCode){
        String format = "{\n" +
                "    \"packageCode\": \"%s\",\n" +
                "    \"tenantId\": \"%s\"\n" +
                "}";
        HttpRequest.post("oms-service.box-tools.com/test/push2om")
                .body(String.format(format,packageCode,tenantId))
                .execute();
    }

    private void syncOrderEs(String tenantId,String omOrderId){
        String format = "{\n" +
                "    \"omOrderId\": \"%s\",\n" +
                "    \"tenantId\": \"%s\"\n" +
                "}";
        HttpRequest.post("oms-service.box-tools.com/test/push2om")
                .body(String.format(format,omOrderId,tenantId))
                .execute();
    }

    private void executorSql(String sql, String tenantId) {
        try {
            String result = HttpRequest.get("http://opms-service.box-tools.com/client/tenant/db_config_list?appCode=" + "oms").execute().body();
            TenantDbDTO tenantDbDTO = JSONUtil.toBean(result, TenantDbDTO.class);

            Optional<TenantDbDTO.DataBean> optional = tenantDbDTO.getData().stream().filter(tenantDb -> tenantDb.getTenantId().equals(tenantId)).findFirst();
            if (!optional.isPresent()) {
                throw new RuntimeException("数据源不存在!");
            }
            TenantDbDTO.DataBean dataBean = optional.get();
            Connection connection = DriverManager.getConnection(dataBean.getDbUrl(), dataBean.getUsername(), dataBean.getPassword());
            ScriptRunner scriptRunner = new ScriptRunner(connection);
            scriptRunner.setStopOnError(true);
            scriptRunner.runScript(new StringReader(sql));
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
